package com.maidou.qiantai.service.impl;

import java.util.Date;
import java.util.List;

import com.maidou.qiantai.api.OssServiceApi;
import com.maidou.qiantai.common.utils.jwt.JwtUtils;
import com.maidou.qiantai.common.utils.util.FileUploadUtil;
import com.maidou.qiantai.common.utils.util.WebUtils;
import com.maidou.qiantai.domain.MemberLevel;
import com.maidou.qiantai.dto.member.LoginDto;
import com.maidou.qiantai.dto.member.MemberInfoDto;
import com.maidou.qiantai.dto.member.PwdDto;
import com.maidou.qiantai.vo.member.LoginVo;
import com.maidou.qiantai.vo.member.MemberVo;
import com.ruoyi.common.utils.DateUtils;
import lombok.extern.log4j.Log4j;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import com.maidou.qiantai.mapper.MemberMapper;
import com.maidou.qiantai.domain.Member;
import com.maidou.qiantai.service.IMemberService;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * 用户Service业务层处理
 * 
 * @author maidou
 * @date 2024-03-13
 */
@Log4j2
@Service
public class MemberServiceImpl implements IMemberService 
{
    @Resource
    private MemberMapper memberMapper;

    @Resource
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Resource
    private MemberLevelServiceImpl memberLevelService;

    @Resource
    private OssServiceApi ossServiceApi;

    /**
     * 查询用户
     * 
     * @param id 用户主键
     * @return 用户
     */
    @Override
    public Member selectMemberById(Long id)
    {
        return memberMapper.selectMemberById(id);
    }

    /**
     * 查询用户列表
     * 
     * @param member 用户
     * @return 用户
     */
    @Override
    public List<Member> selectMemberList(Member member)
    {
        return memberMapper.selectMemberList(member);
    }

    /**
     * 新增用户
     * 
     * @param member 用户
     * @return 结果
     */
    @Override
    public int insertMember(Member member)
    {
        member.setCreateTime(DateUtils.getNowDate());
        return memberMapper.insertMember(member);
    }

    /**
     * 修改用户
     * 
     * @param member 用户
     * @return 结果
     */
    @Override
    public int updateMember(Member member)
    {
        member.setUpdateTime(DateUtils.getNowDate());
        return memberMapper.updateMember(member);
    }

    /**
     * 批量删除用户
     * 
     * @param ids 需要删除的用户主键
     * @return 结果
     */
    @Override
    public int deleteMemberByIds(Long[] ids)
    {
        return memberMapper.deleteMemberByIds(ids);
    }

    /**
     * 删除用户信息
     * 
     * @param id 用户主键
     * @return 结果
     */
    @Override
    public int deleteMemberById(Long id)
    {
        return memberMapper.deleteMemberById(id);
    }

    /**
     * 登录注册
     * @param loginDto
     * @return
     */
    @Override
    public LoginVo login(LoginDto loginDto) {
        String username = loginDto.getUsername();
        //判断是否有此用户
        Member member = new Member();
        member.setUsername(username);
        List<Member> members = memberMapper.selectMemberList(member);
        Long id = null;
        if (members.isEmpty()||members.size()==0){
        //注册
            MemberLevel memberLevel = new MemberLevel();
            memberLevel.setDefaultStatus(1);
            List<MemberLevel> memberLevels = memberLevelService.selectMemberLevelList(memberLevel);
            if (memberLevels==null||memberLevels.isEmpty()||memberLevels.size()==0) {
                member.setLevelId(1l);
            }
            else {
                MemberLevel memberLevel1 = memberLevels.get(0);
                member.setLevelId(memberLevel1.getId());
            }
            String encode = bCryptPasswordEncoder.encode(loginDto.getPassword());
            member.setPassword(encode);
            member.setGrowth(0l);
            member.setIntegration(0l);
            member.setStatus(0);
            member.setSourceType(0);
            member.setLastLoginTime(new Date());
            member.setAccountPermission(0);
            memberMapper.insertMember(member);
            id=member.getId();
        }else{
            //登录
            Member member1 = members.get(0);
            String password = member1.getPassword();
            boolean matches = bCryptPasswordEncoder.matches(loginDto.getPassword(), password);
            if (!matches){
                throw new RuntimeException("密码错误");
            }
            id = member1.getId();
        }
        String accessToken = JwtUtils.generateAccessToken(id);
        LoginVo vo = new LoginVo();
        vo.setToken(accessToken);
        MemberVo memberVo = selectUserinfoById(id);
        vo.setMemberVo(memberVo);
        return vo;
    }

    /**
     * 获取用户基本信息
     * @return
     */
    @Override
    public MemberVo selectUserinfo() {
        Long id = WebUtils.getMemberIdByAccessToken();
        Member member = selectMemberById(id);
        MemberVo memberVo = new MemberVo();
        BeanUtils.copyProperties(member,memberVo);
        Long levelId = member.getLevelId();
        MemberLevel memberLevel = memberLevelService.selectMemberLevelById(levelId);
        memberVo.setMemberLevel(memberLevel);
        return memberVo;
    }

    /**
     * 修改用户信息
     * @param memberInfoDto
     * @return
     */
    @Override
    public Integer updateMemberInfo(MemberInfoDto memberInfoDto) {
        Member member = new Member();
        BeanUtils.copyProperties(memberInfoDto,member);
        return memberMapper.updateMember(member);
    }

    /**
     * 修改密码
     * @param pwdDto
     * @return
     */
    @Override
    public Integer updateMemberEditPwd(PwdDto pwdDto) {
        Long memberId = WebUtils.getMemberIdByAccessToken();
        Member member = selectMemberById(memberId);
        String odepwd = pwdDto.getOdepwd();
        boolean matches = bCryptPasswordEncoder.matches(odepwd, member.getPassword());
        if (!matches){
            throw new RuntimeException("密码错误");
        }
        String encode = bCryptPasswordEncoder.encode(pwdDto.getConfirmnewpwd());
        member.setPassword(encode);
        return updateMember(member);
    }

    /**
     * 修改头像
     * @param multipartFile
     * @return
     */
    @Override
    public String updateMemberEditHeader(MultipartFile multipartFile) {
        String url = ossServiceApi.OssUpload(multipartFile, null);
        Long memberId = WebUtils.getMemberIdByAccessToken();
        Member member = memberMapper.selectMemberById(memberId);
        String header = member.getHeader();
        if (!ObjectUtils.isEmpty(header)){
            try {
                ossServiceApi.deleteFile(header);
            }catch (Exception e){
                log.error("删除头像失败，可能是无此文件");
            }
        }
        member.setHeader(url);
        memberMapper.updateMember(member);
        return url;
    }

    /**
     * 获取用户基本信息
     * @return
     */
    public MemberVo selectUserinfoById(Long id) {
        Member member = selectMemberById(id);
        MemberVo memberVo = new MemberVo();
        BeanUtils.copyProperties(member,memberVo);
        Long levelId = member.getLevelId();
        MemberLevel memberLevel = memberLevelService.selectMemberLevelById(levelId);
        memberVo.setMemberLevel(memberLevel);
        return memberVo;
    }
}
